package com.study.zookeeper.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @author flwu
 * @date 2020/3/19 10:36 PM
 * @MOTTO 保持空杯和敬畏
 */
@Configuration
@PropertySource("classpath:curator.properties")
public class ZookeeperConfig {

    @Value(value = "${curator.connect-string}")
    private String connectString;

    @Value(value = "${curator.retry-policy}")
    private Integer retryPolicy;

    @Value(value = "${curator.session-timeout-ms}")
    private Integer sessionTimeoutMs;

    @Value(value = "${curator.connection-timeout-ms}")
    private Integer connectionTimeoutMs;

    @Value(value = "${curator.name-space}")
    private String nameSpace;

    @Value(value = "${curator.retry-interval}")
    private Integer retryInterval;

    @Bean
    public CuratorFramework curatorClient() {
        //构建重试机制实例
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(this.retryInterval, this.retryPolicy);
        //初始化curator
        CuratorFramework curatorClient = CuratorFrameworkFactory.builder().connectString(this.connectString)
                .sessionTimeoutMs(this.sessionTimeoutMs).connectionTimeoutMs(this.connectionTimeoutMs)
                .retryPolicy(retryPolicy).namespace(this.nameSpace).build();
        curatorClient.start();
        return curatorClient;
    }

}

